package com.bjsxt.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

public class TestZookeeper {
    public static void main(String[] args) throws Exception{
        // create();
        //listKey();
        //get();
        delete();
    }
    /**
     * 删除节点
     * 删除节点，需要先查询节点的状态（cversion）,通过getData来查询这个版本。
     * 设计是为了保证删除的节点是你想要删除的那个。
     * */
    public static void delete()throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("172.21.50.135:2181", 100000, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("连接对象创建");
            }
        });
        //获取节点信息
        Stat stat = new Stat();
        System.out.println(stat);
        zooKeeper.getData("/parent/sequence0000000001",false,stat);
        System.out.println(stat.getCversion());
        //删除
        zooKeeper.delete("/parent/sequence0000000001",stat.getCversion());


    }



    /**
    * 查询节点中存储的数据，相当于根据key获取value
    * */
    public static void get() throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("172.21.50.135:2181", 100000, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("zookeeper 对象被创建了");
            }
        });
        //获取数据
        byte[] datas=zooKeeper.getData("/parent",false,null);
        System.out.println("节点/parent中存储的数据是："+new String(datas));
    }

    /**
     * 查询节点，相当于遍历key
    * */
    public static void listKey()throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("172.21.50.135:2181", 100000, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("连接被创建了");
            }
        });
        //遍历zk中所有的节点
        listAll(zooKeeper,"/");
     /*   List<String> children=zooKeeper.getChildren("/",false);
        for (String child :
                children) {
            System.out.println(child);
        }*/

    }
    /*
    * 迭代
    * */
    private static void listAll(ZooKeeper zooKeeper,String path)throws Exception{
        List<String> children = zooKeeper.getChildren(path,false);
        for (String child :
                children) {
            String currentNodeName="/".equals(path)?(path+child):(path+"/"+child);
            System.out.println(currentNodeName);
            listAll(zooKeeper,currentNodeName);
        }
    }


    /**
    * 使用JAVA远程访问zk，步骤是：
    * 1、创建客户端
    * 2、使用客户端发送命令
    * 3、处理返回结果
    * 4、回收资源
    *
    * 什么是会话？
    * 持久，长期，有状态。
    * */
    public static void create() throws IOException, KeeperException, InterruptedException {
        //创建客户端对象
        ZooKeeper zooKeeper = new ZooKeeper("172.21.50.135:2181", 100000, new Watcher() {

            public void process(WatchedEvent watchedEvent) {
                System.out.println("客户端创建成功了，这里是watcher执行了！");
            }
        });
        /*
        * 创建一个节点
        * path - 路径
        * data - 对应的值
        * ZooDefs.Ids.CREATOR_ALL_ACL   _ 赋全部的权限
        * CreateMode.PERSISTENT - 创建的模式：普通的持久的。（持久，临时，持久带序列号，持久不带序列号，临时带序列号）
        * */
        //创建一个节点
        if(zooKeeper.exists("/parent", false) == null) {
            String result = zooKeeper.create("/parent", "parent data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("创建parent节点结果："+result);
        }
        //
        //创建一个临时节点
        if(zooKeeper.exists("/parent", false) == null) {
            String TempResult = zooKeeper.create("/parent/tmp", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            System.out.println("创建/parent/tmp节点的输出：" + TempResult);
        }
        //创建一个带序号的节点
        if(zooKeeper.exists("/parent/sequence", false) == null) {
            String seqResult = zooKeeper.create("/parent/sequence", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            System.out.println("创建：/parent/sequence节点输出的结果：" + seqResult);
        }

        //休眠6秒
       // Thread.sleep(6000);
        //关闭客户端
        zooKeeper.close();
    }
}
